package modulesAPI.v2.basics;


import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.caterina.components.CLabel;
import com.caterina.components.CPanel;
import com.caterina.components.CTextField;
import com.caterina.resources.CColors;
import com.caterina.resources.CModules;

import modulesAPI.v2.Module;
import modulesAPI.v2.ViewType;

public class ModIntTextField extends Module<Integer> implements DocumentListener{
	/**
	 * Crea un nuovo modulo per l'inserimento/rappresentazione di interi
	 * */
	public ModIntTextField(Module<?> ownerModule, Integer content, String tag,String description, ViewType viewType) {
		super(ownerModule, content, tag, description, viewType);
	}
	@Override
	protected CPanel getReadOnlyPanel(boolean isSelected) {
		return CModules.formatPanelForReadOnlyPairs(this.getTag(), this.getContent().toString());
	}
	@Override
	protected CPanel getWritablePanel(boolean isSelected) {
		this.textField=new CTextField(this.getContent().toString(), 20, this.getDescription());
		this.textField.getDocument().addDocumentListener(this);
		return CModules.formatForPairs(this.getTag(), textField);
	}
	@Override
	public CPanel getInListPanel(boolean isSelected) {
		CPanel retPanel=new CPanel();
		retPanel.add(new CLabel(this.getContent().toString()));
		return retPanel;
	}
	@Override
	public void changedUpdate(DocumentEvent e) {
		this.verify();
	}
	@Override
	public void insertUpdate(DocumentEvent e) {
		this.verify();
	}
	@Override
	public void removeUpdate(DocumentEvent e) {
		this.verify();
	}
	@Override
	protected void beforeFireChange(Module<?> mod) {}
	
	private void verify(){
		if(this.textField.getText().matches("((^-|)[0-9]{1,9})")){
			this.setContent(Integer.parseInt(this.textField.getText()));
			this.textField.setForeground(CColors.BLACK);
		}else{
			this.textField.setForeground(CColors.BUTTON_NORMAL_CATERINA);
			this.setContent(0);
			}
		this.fireModuleChanged(this);
	}
	@Override
	protected void afterFireChange(Module<?> mod) {}
	@Override
	protected CPanel getOneLinePanel(boolean isSelected) {
		return this.getReadOnlyPanel(isSelected);
	}
	private CTextField textField;
}
